﻿using System.Collections.Generic;
using System.Threading.Tasks;
using Jinjia.Approve.Entity.Entity.JJFlow;
using Jinjia.Approve.IRepository.JJFlow;
using Jinjia.Core.UnitOfWork.UnitOfWorkComponent;
using SqlSugar;

namespace Jinjia.Approve.Repository.JJFlow
{
    public class FlowStepRepository : IFlowStepRepository
    {
        private readonly ISqlSugarClient _db;

        public FlowStepRepository(IUnitOfWork unitOfWork)
        {
            _db = unitOfWork.GetDbClient();
        }

        public async Task<jj_flow_step> GetById(int step_id)
        {
            var jjFlowStep = await _db.Queryable<jj_flow_step>().Where(x => x.id == step_id).FirstAsync();
            return jjFlowStep;
        }

        public async Task<List<jj_flow_step>> GetNextPossiblePath(int node_id)
        {
            return await _db.Queryable<jj_flow_step>().Where(x => x.from_node == node_id && x.deleted == 0).OrderBy(x => x.priority, OrderByType.Desc).ToListAsync();
        }

        public async Task<List<jj_flow_step>> GetByTemplateId(int template_id)
        {
            return await _db.Queryable<jj_flow_step>()
                .Where(x => x.template_id == template_id)
                .Where(x => x.deleted == 0)
                .ToListAsync();
        }

        public async Task<int> Save(jj_flow_step data)
        {
            if (data.id <= 0) //新增
            {
                var id = await _db.Insertable(data).ExecuteReturnIdentityAsync();
                return id;
            }
            else
            {
                await _db.Updateable(data)
                    .Where(x => x.id == data.id)
                    .ExecuteCommandAsync();
                return data.id;
            }
        }
    }
}